package com.adcc.ags.gms.gw.service;


import com.adcc.ags.gms.core.entity.GWLog;
import com.adcc.ags.gms.core.entity.GWLogLevel;
import com.adcc.ags.gms.core.mapper.GWLogMapper;
import com.adcc.ags.gms.core.util.*;
import com.adcc.ags.gms.gw.vo.*;
import com.adcc.ags.gms.mq.service.QMService;
import com.adcc.ags.gms.mq.vo.QMVO;
import com.adcc.ags.gms.user.entity.GWUser;
import com.adcc.ags.gms.user.mapper.GWUserMapper;
import com.adcc.utility.mq.manager.MQManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户监控服务实现层
 */
@Service("UserMonitorService")
public class UserMonitorServiceImpl implements UserMonitorService {

    //后加
    @Autowired
    private GWUserMapper gwUserMapper;
    @Autowired
    private MQFactory mqFactory;
    @Autowired
    private SysConfigurationService sysConfigurationService;
    @Autowired
    private LogFactory log;
    @Autowired
    private QMService qmService;
    @Autowired
    private AppConfiguration appConfiguration;
    @Autowired
    private GWLogMapper gwLogMapper;

    //用户状态集合
    private static Map<String, Map<String, String>> userStates = new ConcurrentHashMap<>();
    //用户监控数据
    private static List<UserMonitorVO> allUserMonitor = Collections.synchronizedList(new ArrayList<UserMonitorVO>());
    //系统监控数据
    private static Map<String, Object> sysMonitor = new ConcurrentHashMap<>();

    //系统监控告警记录
    private static Map<String, Map<String, String>> sysMonitorWarn = new ConcurrentHashMap<>();

    /**
     * 获取所有用户监控（四种状态）
     * 2016-12-22 liuyi更新
     *
     * @return
     */
    @Override
    public Optional<List<UserMonitorVO>> findAllUserMonitor() {
        try {
            if (!CacheStack.getUserMonitorStack().empty()) {
                if (CacheStack.getUserMonitorStack().peek() != null) {
                    return Optional.of(CacheStack.getUserMonitorStack().peek());
                }
            }
        } catch (Exception e) {
            log.error(UserMonitorService.class, "findAllUserMonitor() error", e);
        }
        return Optional.absent();
    }

    /**
     * 获取所有系统监控
     *
     * @return
     */
    @Override
    public Optional<Map<String, Object>> findAllSysMonitor() {
        try {
            if (!CacheStack.getSysMonitorStack().empty()) {
                if (CacheStack.getSysMonitorStack().peek() != null) {
                    return Optional.of(CacheStack.getSysMonitorStack().peek());
                }
            }
        } catch (Exception e) {
            log.error(UserMonitorService.class, "findAllSysMonitor() error", e);
        }
        return Optional.absent();
    }

    /**
     * 系统监控告警事件
     *
     * @return
     */
    @Override
    public Optional<Map<String, Map<String, String>>> getSysMonitorWarn() {
        try {
            return Optional.of(sysMonitorWarn);
        } catch (Exception e) {
            log.error(UserMonitorService.class, "getSysMonitorWarn() error", e);
            return Optional.absent();
        }

    }

    /**
     * 用户监控告警事件
     *
     * @return
     */
    @Override
    public Optional<Map<String, String>> getUserMonitorWarn() {
        Map<String, String> map = new ConcurrentHashMap<>();
        try {
            Optional<List<UserMonitorVO>> optional = findAllUserMonitor();
            if (optional.isPresent()) {
                for (UserMonitorVO userMonitorVO : optional.get()) {
                    if (userMonitorVO.getState() == 1) {//掉线
                        map.put(userMonitorVO.getName(), "OFFLINE");
                    } else if (userMonitorVO.getState() == 2) {//告警
                        map.put(userMonitorVO.getName(), "BLOCKING");
                    } else if (userMonitorVO.getState() == 3) {//正常
                        map.put(userMonitorVO.getName(), "ONLINE");
                    }
                }
            }
            return Optional.of(map);
        } catch (Exception e) {
            log.error(UserMonitorService.class, "getUserMonitorWarn() error", e);
            return Optional.absent();
        }
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @Override
    public Optional<List<String>> getGwUserList() {
        List<String> list = Collections.synchronizedList(new ArrayList<String>());
        try {
            List<GWUser> gwUsers = gwUserMapper.findAllGWUser();
            for (GWUser gwUser : gwUsers) {
                list.add(gwUser.getUserName());
            }
            return Optional.of(list);
        } catch (Exception e) {
            log.error(UserMonitorService.class, "getGwUserList() error", e);
            return Optional.absent();
        }

    }

    /**
     * 获取日志列表
     *
     * @param dateStart
     * @param dateEnd
     * @return
     */
    @Override
    public Optional<List<GWLogVO>> getGWLogList(String dateStart, String dateEnd) {
        try {
            List<GWLogVO> voList = gwLogMapper.findAllWarnLogs(dateStart, dateEnd);
            return Optional.of(voList);
        } catch (Exception e) {
            log.error(UserMonitorService.class, "getGWlogList() error", e);
            return Optional.absent();
        }
    }

    /**
     * amqs监控
     *
     * @return
     */
    public Optional<AMQSMonitorVO> getAmqsMonitor(Map<String, LinkedHashMap<String, String>> map) {
        AMQSMonitorVO amqsMonitorVO = new AMQSMonitorVO();
        try {
            if (map != null) {
                LinkedHashMap<String, String> gwMap = map.get("amqs");
                Map<String, Map<String, String>> map1 = new ObjectMapper().readValue(gwMap.get("message"), Map.class);
                boolean healthy = Boolean.valueOf(new ObjectMapper().writeValueAsString(gwMap.get("healthy")));
                amqsMonitorVO.setUpdateTime(new ObjectMapper().writeValueAsString(map1.get("updateTime")).replace("\"", ""));
                Map<String, String> mqMap = map1.get("mq");
                amqsMonitorVO.setChannel(mqMap.get("channel"));
                amqsMonitorVO.setPort(mqMap.get("port"));
                amqsMonitorVO.setHost(mqMap.get("host"));
                amqsMonitorVO.setState(mqMap.get("state"));
                amqsMonitorVO.setQm(mqMap.get("qm"));
                amqsMonitorVO.setHealthy(healthy);
            }
            return Optional.of(amqsMonitorVO);
        } catch (IOException e) {
            log.error(UserMonitorServiceImpl.class, "SysMonitor", GWLogLevel.ALARM, "getAmqsMonitor() error", e);
            return Optional.absent();
        }
    }

    /**
     * mq监控
     *
     * @return
     */
    public Optional<MQInfoMonitorVO> getMqMonitor() {
        MQInfoMonitorVO mqInfoMonitorVO = new MQInfoMonitorVO();
        try {
            Optional<List<QMVO>> optional = qmService.getAllQMByPCF();
            if (optional.isPresent() && optional.get().size() > 0) {
                QMVO qmvo = optional.get().get(0);
                mqInfoMonitorVO.setHost(qmvo.getIp());
                mqInfoMonitorVO.setName(qmvo.getName());
                mqInfoMonitorVO.setConnectCount(qmvo.getConnectCount());
                mqInfoMonitorVO.setPort(qmvo.getPort());
                mqInfoMonitorVO.setState(qmvo.getStatus());
                mqInfoMonitorVO.setStartTime(qmvo.getStartTime());
            }
            return Optional.of(mqInfoMonitorVO);
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "SysMonitor", GWLogLevel.ALARM, "getMqMonitor() error", e);
            mqInfoMonitorVO.setName(appConfiguration.getSourceMQQM());
            mqInfoMonitorVO.setHost(appConfiguration.getSourceMQIP());
            mqInfoMonitorVO.setPort(appConfiguration.getSourceMQPort());
            return Optional.of(mqInfoMonitorVO);
        }
    }

    /**
     * gw监控
     *
     * @param map
     * @return
     */
    public Optional<GWMonitorVO> getGWMonitor(Map<String, LinkedHashMap<String, String>> map) {
        //结果集
        GWMonitorVO gwMonitorVO = new GWMonitorVO();
        try {
            if (map != null) {
                LinkedHashMap<String, String> gwMap = map.get("gw");
                Map<String, Map<String, String>> map1 = new ObjectMapper().readValue(gwMap.get("message"), Map.class);
                boolean healthy = Boolean.valueOf(new ObjectMapper().writeValueAsString(gwMap.get("healthy")));

                Map<String, String> mqMap = map1.get("mq");
                //GW 名称  IP
                String gwName = new ObjectMapper().writeValueAsString(map1.get("name")).replace("\"", "");
                String gwHost = new ObjectMapper().writeValueAsString(map1.get("host")).replace("\"", "");
                String updateTime = new ObjectMapper().writeValueAsString(map1.get("updateTime")).replace("\"", "");
                gwMonitorVO.setUpdateTime(updateTime);
                // name ip 匹配上
                if ((gwName.equals(sysConfigurationService.getValue(Constant.GW_MASTER_NAME)) && gwHost.equals(sysConfigurationService.getValue(Constant.GW_MASTER_IP))) || (gwName.equals(sysConfigurationService.getValue(Constant.GW_SLAVE_NAME)) && gwHost.equals(sysConfigurationService.getValue(Constant.GW_SLAVE_IP)))) {
                    gwMonitorVO.setName(gwName);
                    gwMonitorVO.setIp(gwHost);
                    gwMonitorVO.setChannel(mqMap.get("channel"));
                    gwMonitorVO.setPort(mqMap.get("port"));
                    gwMonitorVO.setHost(mqMap.get("host"));
                    gwMonitorVO.setState(mqMap.get("state"));
                    gwMonitorVO.setHealthy(healthy);
                    gwMonitorVO.setQm(mqMap.get("qm"));
                    String mode = new ObjectMapper().writeValueAsString(map1.get("mode"));
                    gwMonitorVO.setMode(mode.replace("\"", ""));
                } else {
                    String mode = new ObjectMapper().writeValueAsString(map1.get("mode"));
                    gwMonitorVO.setMode(mode.replace("\"", ""));
                }
            } else {//CGW服务没有开启一异常情况(默认显示主用)
                gwMonitorVO.setName(sysConfigurationService.getValue(Constant.GW_MASTER_NAME));
                gwMonitorVO.setIp(sysConfigurationService.getValue(Constant.GW_MASTER_IP));
            }
            return Optional.of(gwMonitorVO);
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "SysMonitor", GWLogLevel.ALARM, "getGWMonitor() error", e);
            return Optional.absent();
        }

    }

    /**
     * 用户监控及系统监控数据获取
     */
    @Override
    public void refreshData() {
        try {
            Map<String, LinkedHashMap<String, String>> map = getRestService(sysConfigurationService.getValue(Constant.USER_MONITOR_URL));
            //系统监控模块
            refreshSysMonitor(map);

            //用户监控模块
            refreshUserMonitor(map);
        } catch (Exception e) {
            log.error(UserMonitorService.class, "用户监控", GWLogLevel.SERIOUS_ALARM, "获取用户监控信息异常");
        }
    }

    /**
     * 系统监控数据刷新
     *
     * @param map
     */
    public void refreshSysMonitor(Map<String, LinkedHashMap<String, String>> map) {
        try {
            Map<String, Object> sysMonitorMap = new ConcurrentHashMap<>();
            //AMQS
            AMQSMonitorVO amqsMonitorVO = getAmqsMonitor(map).isPresent() ? getAmqsMonitor(map).get() : null;
            sysMonitorMap.put("AMQS", amqsMonitorVO);
            //MQ
            MQInfoMonitorVO mqInfoMonitorVO = getMqMonitor().isPresent() ? getMqMonitor().get() : null;
            sysMonitorMap.put("MQ", mqInfoMonitorVO);
            //GW
            GWMonitorVO gwMonitorVO = getGWMonitor(map).isPresent() ? getGWMonitor(map).get() : null;
            sysMonitorMap.put("GW", gwMonitorVO);
            sysLogRecord(amqsMonitorVO, mqInfoMonitorVO, gwMonitorVO);
            sysMonitor = sysMonitorMap;
            //新数据压入栈顶
            CacheStack.getSysMonitorStack().push(sysMonitor);
            if (CacheStack.getSysMonitorStack().size() > 2) {
                CacheStack.getSysMonitorStack().remove(0);
            }
        } catch (Exception e) {
            log.error(UserMonitorService.class, "refreshSysMonitor() error", e);
        }
    }

    /**
     * 系统监控状态切换日志记录
     *
     * @param amqsMonitorVO
     * @param mqInfoMonitorVO
     * @param gwMonitorVO
     */
    public void sysLogRecord(AMQSMonitorVO amqsMonitorVO, MQInfoMonitorVO mqInfoMonitorVO, GWMonitorVO gwMonitorVO) {
        try {
            Map<String, Map<String, String>> map = new ConcurrentHashMap<>();
            //AMQS日志记录
            AMQSMonitorVO lstTimAmqsMonitorVO = (AMQSMonitorVO) sysMonitor.get("AMQS");
            Map<String, String> AMQSMap = new ConcurrentHashMap<>();
            if (amqsMonitorVO != null && amqsMonitorVO.getQm() != null) {
                //这一次AMQS状态
                Boolean thisTimeHealthy = amqsMonitorVO.isHealthy();
                AMQSMap.put("name", amqsMonitorVO.getQm());
                if (lstTimAmqsMonitorVO != null && lstTimAmqsMonitorVO.getQm() != null) {
                    //上一次AMQS状态
                    Boolean lastTimeHealthy = lstTimAmqsMonitorVO.isHealthy();
                    if (lastTimeHealthy && thisTimeHealthy) {//正常-正常
                        AMQSMap.put("state", "CONNECTED");
                    } else if (!lastTimeHealthy && thisTimeHealthy) {//异常-正常
                        log.info(UserMonitorService.class, amqsMonitorVO.getQm(), "AMQS监控：正常");
                        AMQSMap.put("state", "CONNECTED");
                    } else if (lastTimeHealthy && !thisTimeHealthy) {//正常-异常
                        log.error(UserMonitorService.class, amqsMonitorVO.getQm(), GWLogLevel.ALARM, "AMQS监控：异常");
                        AMQSMap.put("state", "CONNECTING");
                    } else if (!lastTimeHealthy && !thisTimeHealthy) {//异常-异常，需判断时间
                        if (!Strings.nullToEmpty(amqsMonitorVO.getUpdateTime()).equals(Strings.nullToEmpty(lstTimAmqsMonitorVO.getUpdateTime()))) {
                            log.error(UserMonitorService.class, amqsMonitorVO.getQm(), GWLogLevel.ALARM, "AMQS监控：异常");
                        }
                        AMQSMap.put("state", "CONNECTING");
                    }
                } else {
                    if (thisTimeHealthy) {//正常
                        log.info(UserMonitorService.class, amqsMonitorVO.getQm(), "AMQS监控：正常");
                        AMQSMap.put("state", "CONNECTED");
                    } else if (!thisTimeHealthy) {//异常
                        log.error(UserMonitorService.class, amqsMonitorVO.getQm(), GWLogLevel.ALARM, "AMQS监控：异常");
                        AMQSMap.put("state", "CONNECTING");
                    }
                }
            } else {
                if (lstTimAmqsMonitorVO != null) {
                    if (!Strings.nullToEmpty(amqsMonitorVO.getUpdateTime()).equals(Strings.nullToEmpty(lstTimAmqsMonitorVO.getUpdateTime()))) {
                        log.error(UserMonitorService.class, "AMQS", GWLogLevel.ALARM, "AMQS监控：获取心跳失败");
                    }
                } else {
                    log.error(UserMonitorService.class, "AMQS", GWLogLevel.ALARM, "AMQS监控：获取心跳失败");
                }
                AMQSMap.put("name", "AMQS");
//                AMQSMap.put("state", "ERROR");
                AMQSMap.put("state", "CONNECTING");
            }
            map.put("AMQS", AMQSMap);


            //MQ日志记录
            MQInfoMonitorVO lstTimeMqInfoMonitorVO = (MQInfoMonitorVO) sysMonitor.get("MQ");
            Map<String, String> MQMap = new ConcurrentHashMap<>();
            MQMap.put("connectCount", String.valueOf(mqInfoMonitorVO.getConnectCount()));
            int intConns = Integer.valueOf(sysConfigurationService.getValue(Constant.MQ_QM_CONNS));
            if (mqInfoMonitorVO != null) {
                if (mqInfoMonitorVO.getConnectCount() > intConns) {
                    MQMap.put("connectCountState", "WARNING");
                } else {
                    MQMap.put("connectCountState", "OK");
                }
            }
            if (mqInfoMonitorVO != null && mqInfoMonitorVO.getState() != null) {
                //这一次MQ状态
                String thisTimeState = mqInfoMonitorVO.getState();
                MQMap.put("name", mqInfoMonitorVO.getName().trim());
                if (lstTimeMqInfoMonitorVO != null && lstTimeMqInfoMonitorVO.getState() != null) {
                    String lastTimeState = lstTimeMqInfoMonitorVO.getState();
                    if ("Running".equals(lastTimeState) && "Running".equals(thisTimeState)) {//正常-正常
                        MQMap.put("state", "RUNNING");
                    } else if (!"Running".equals(lastTimeState) && "Running".equals(thisTimeState)) {//异常-正常
                        log.info(UserMonitorService.class, mqInfoMonitorVO.getName(), "MQ监控：正常");
                        MQMap.put("state", "RUNNING");
                    } else if ("Running".equals(lastTimeState) && !"Running".equals(thisTimeState)) {//正常-异常
                        log.error(UserMonitorService.class, mqInfoMonitorVO.getName(), GWLogLevel.ALARM, "MQ监控：异常");
                        MQMap.put("state", "STOP");
                    } else if (!"Running".equals(lastTimeState) && !"Running".equals(thisTimeState)) {//异常-异常，需判断更新时间
                        log.error(UserMonitorService.class, mqInfoMonitorVO.getName(), GWLogLevel.ALARM, "MQ监控：异常");
                        MQMap.put("state", "STOP");
                    }
                } else {
                    if ("Running".equals(thisTimeState)) {//正常
                        log.info(UserMonitorService.class, mqInfoMonitorVO.getName(), "MQ监控：正常");
                        MQMap.put("state", "RUNNING");
                    } else if (!"Running".equals(thisTimeState)) {
                        log.error(UserMonitorService.class, mqInfoMonitorVO.getName(), GWLogLevel.ALARM, "MQ监控：异常");
                        MQMap.put("state", "STOP");
                    }
                }
            } else {
                log.error(UserMonitorService.class, "MQ", GWLogLevel.ALARM, "MQ监控：异常");
                MQMap.put("name", "MQ");
                MQMap.put("state", "STOP");
            }
            map.put("MQ", MQMap);

            //GW日志记录
            GWMonitorVO lstTimeGwMonitorVO = (GWMonitorVO) sysMonitor.get("GW");
            Map<String, String> GWMap = new ConcurrentHashMap<>();
            if (gwMonitorVO != null && gwMonitorVO.getName() != null) {

                String thisTimeName = gwMonitorVO.getName();
                Boolean thisTimeHealthy = gwMonitorVO.isHealthy();
                GWMap.put("name", thisTimeName);
                if (lstTimeGwMonitorVO != null && lstTimeGwMonitorVO.getName() != null) {

                    String lstTimeName = lstTimeGwMonitorVO.getName();
                    Boolean lstTimeHealthy = lstTimeGwMonitorVO.isHealthy();
                    if (lstTimeHealthy == null && thisTimeHealthy == null) {//CGW异常-CGW异常（需加时间字段判断）
                        if (!Strings.nullToEmpty(gwMonitorVO.getUpdateTime()).equals(Strings.nullToEmpty(lstTimeGwMonitorVO.getUpdateTime()))) {
                            log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：获取心跳失败");
                        }
//                        GWMap.put("state", "ERROR");
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", "");
                    } else if (lstTimeHealthy == null && thisTimeHealthy != null && thisTimeHealthy) {//CGW异常-正常
                        log.info(UserMonitorService.class, thisTimeName, "GW监控：正常");
                        GWMap.put("state", "CONNECTED");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    } else if (lstTimeHealthy == null && thisTimeHealthy != null && !thisTimeHealthy) {//CGW异常-异常
                        log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：异常");
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    } else if (lstTimeHealthy != null && lstTimeHealthy && thisTimeHealthy == null) {//正常-CGW异常
                        log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：获取心跳失败");
//                        GWMap.put("state", "ERROR");
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", "");
                    } else if (lstTimeHealthy != null && lstTimeHealthy && thisTimeHealthy != null && thisTimeHealthy) {//正常-正常(名字不同的记录)
                        if (!lstTimeName.equals(thisTimeName)) {
                            log.info(UserMonitorService.class, thisTimeName, "GW监控：正常");
                        }
                        GWMap.put("state", "CONNECTED");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    } else if (lstTimeHealthy != null && lstTimeHealthy && thisTimeHealthy != null && !thisTimeHealthy) {//正常-异常
                        log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：异常");
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    } else if (lstTimeHealthy != null && !lstTimeHealthy && thisTimeHealthy == null) {//异常-CGW异常
                        log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：获取心跳失败");
//                        GWMap.put("state", "ERROR");
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", "");
                    } else if (lstTimeHealthy != null && !lstTimeHealthy && thisTimeHealthy != null && thisTimeHealthy) {//异常-正常
                        log.info(UserMonitorService.class, thisTimeName, "GW监控：正常");
                        GWMap.put("state", "CONNECTED");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    } else if (lstTimeHealthy != null && !lstTimeHealthy && thisTimeHealthy != null && !thisTimeHealthy) {//异常-异常
                        if (!Strings.nullToEmpty(gwMonitorVO.getUpdateTime()).equals(Strings.nullToEmpty(lstTimeGwMonitorVO.getUpdateTime()))) {
                            log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：异常");
                        }
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    }
                } else {
                    if (thisTimeHealthy == null) {
                        log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：获取心跳失败");
//                        GWMap.put("state", "ERROR");
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", "");
                    } else if (thisTimeHealthy != null && thisTimeHealthy) {
                        log.info(UserMonitorService.class, thisTimeName, "GW监控：正常");
                        GWMap.put("state", "CONNECTED");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    } else if (thisTimeHealthy != null && !thisTimeHealthy) {
                        log.error(UserMonitorService.class, thisTimeName, GWLogLevel.ALARM, "GW监控：异常");
                        GWMap.put("state", "CONNECTING");
                        GWMap.put("mode", gwMonitorVO.getMode());
                    }
                }
            } else {
                if (lstTimAmqsMonitorVO == null || (lstTimeGwMonitorVO != null && lstTimeGwMonitorVO.getName() != null)) {
                    log.error(UserMonitorService.class, "GW", GWLogLevel.ALARM, "GW监控：GW配置异常");
                }
                GWMap.put("name", "GW");
//                GWMap.put("state", "CONFERROR");
                GWMap.put("state", "CONNECTING");
                GWMap.put("mode", gwMonitorVO.getMode());
            }
            map.put("GW", GWMap);
            sysMonitorWarn = map;
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "sysLogRecord() error", e);
        }
    }

    /**
     * 用户监控数据刷新
     *
     * @param map
     */
    public void refreshUserMonitor(Map<String, LinkedHashMap<String, String>> map) {
        try {
            Map<String, Map<String, String>> userStatesMap = new ConcurrentHashMap<>();
            //获取所有的用户配置
            List<GWUser> gwUserList = gwUserMapper.findAllGWUser();
            //获取CGW用户状态
            Map<String, Object> result = getCGWUserStates(map);
            //结果集
            List<UserMonitorVO> userMonitorVOs = new ArrayList<>();
            if (result != null) {
                if ((Boolean) result.get("healthy")) {//healthy为true时显示所有
                    Map<String, UserMonitorVO> CGWUserMap = (Map<String, UserMonitorVO>) result.get("cgwUserSates");
                    //普通模式LL
                    if ("NORMAL".equals(result.get("mode").toString())) {
                        if (gwUserList != null && gwUserList.size() > 0) {
                            for (GWUser gwUser : gwUserList) {
                                UserMonitorVO userMonitorVO = normalMode(gwUser, CGWUserMap);
                                userMonitorVOs.add(userMonitorVO);
                                //日志记录
                                userStatesMap.put(userMonitorVO.getName(), dataRecAndUpdate(userMonitorVO));
                            }
                        }
                    } else if ("EMERGENCY".equals(result.get("mode").toString())) {//应急模式
                        List<GWUser> delGwUserList = new ArrayList<>();
                        //过滤库中与rest匹配的用户(显示rest中与库里没有匹配到的用户)
                        Iterator iter = CGWUserMap.entrySet().iterator();
                        while (iter.hasNext()) {
                            Map.Entry<String, UserMonitorVO> entry = (Map.Entry) iter.next();
                            UserMonitorVO userMonitorVO = null;
                            boolean flag = false;
                            for (GWUser gwUser : gwUserList) {
                                if (entry.getKey().equals(gwUser.getUserId())) {
                                    userMonitorVO = entry.getValue();
                                    userMonitorVO = emergencyMode(userMonitorVO, gwUser);
                                    userMonitorVOs.add(userMonitorVO);
                                    //日志记录
                                    userStatesMap.put(userMonitorVO.getName(), dataRecAndUpdate(userMonitorVO));
                                    //将库中匹配到的用户加入移除集合
                                    delGwUserList.add(gwUser);
                                    flag = true;
                                    break;
                                }
                            }
                            //显示rest中与库里没有匹配到的用户
                            if (!flag) {
                                userMonitorVO = excepMode(entry.getValue(), null);
                                userMonitorVOs.add(userMonitorVO);
                                //日志记录
                                userStatesMap.put(userMonitorVO.getName(), dataRecAndUpdate(userMonitorVO));
                            }
                        }
                        //移除库中所有与rest匹配的用户
                        gwUserList.removeAll(delGwUserList);
                        for (GWUser gwUser : gwUserList) {
                            UserMonitorVO userMonitorVO = emergencyMode(null, gwUser);
                            userMonitorVOs.add(userMonitorVO);
                            //日志记录
                            userStatesMap.put(userMonitorVO.getName(), dataRecAndUpdate(userMonitorVO));
                        }
                    }
                }
            } else {//CGW服务异常
                for (GWUser gwUser : gwUserList) {
                    UserMonitorVO userMonitorVO = excepMode(null, gwUser);
                    userMonitorVOs.add(userMonitorVO);
                    //日志记录以及静态数据更新
                    userStatesMap.put(userMonitorVO.getName(), dataRecAndUpdate(userMonitorVO));
                }
            }
            //更新上一次用户状态集合
            userStates = userStatesMap;
            //排序
            Collections.sort(userMonitorVOs);
            allUserMonitor = userMonitorVOs;
            //新数据压入栈顶
            CacheStack.getUserMonitorStack().push(allUserMonitor);
            if (CacheStack.getUserMonitorStack().size() > 2) {
                CacheStack.getUserMonitorStack().remove(0);
            }
        } catch (Exception e) {
            log.error(UserMonitorService.class, "refreshUserMonitor() error", e);
        }
    }

    /**
     * 用户监控日志记录、静态数据更新
     *
     * @param userMonitorVO
     * @return
     */
    public Map<String, String> dataRecAndUpdate(UserMonitorVO userMonitorVO) {
        Map<String, String> userStatesInfo = null;
        try {
            userLogRecord(userMonitorVO);
            userStatesInfo = new ConcurrentHashMap<>();
            userStatesInfo.put("state", userMonitorVO.getState().toString());
            userStatesInfo.put("updateTime", userMonitorVO.getUpdateTime());
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "dataRecAndUpdate() error", e);
        }
        return userStatesInfo;
    }

    /**
     * 用户状态切换日志记录
     *
     * @param userMonitorVO
     */
    public void userLogRecord(UserMonitorVO userMonitorVO) {
        //上一次用户状态
        Integer lastTimeState = null;
        //新的用户状态
        Integer thisTimeState = userMonitorVO.getState();
        Map<String, String> map = userStates.get(userMonitorVO.getName());
        try {
            if (map != null && map.size() > 0) {
                //相同状态情况下，两次更新时间相同则不记录日志
                boolean flag = Strings.nullToEmpty(map.get("updateTime")).equals(Strings.nullToEmpty(userMonitorVO.getUpdateTime()));

                lastTimeState = Integer.valueOf(map.get("state"));
                if (lastTimeState != null) {
                    //比较两种状态记录日志
                    switch (lastTimeState) {
                        case 1://红
                            switch (thisTimeState) {
                                case 1:
                                    if (!flag) {
                                        log.error(UserMonitorService.class, userMonitorVO.getName(), GWLogLevel.ALARM, "监控用户：" + userMonitorVO.getName() + "掉线");
                                    }
                                    break;
                                case 2:
                                    log.warn(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "队列深度超出阀值");
                                    break;
                                case 3:
                                    log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "上线");
                                    break;
                                case 4:
                                    log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "下线");
                                    break;
                            }
                            break;
                        case 2://黄
                            switch (thisTimeState) {
                                case 1:
                                    log.error(UserMonitorService.class, userMonitorVO.getName(), GWLogLevel.ALARM, "监控用户：" + userMonitorVO.getName() + "掉线");
                                    break;
                                case 2:
                                    if (!flag) {
                                        log.warn(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "队列深度超出阀值");
                                    }
                                    break;
                                case 3:
                                    log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "深度告警解除");
                                    break;
                                case 4:
                                    log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "下线");
                                    break;
                            }
                            break;
                        case 3://绿
                            switch (thisTimeState) {
                                case 1:
                                    log.error(UserMonitorService.class, userMonitorVO.getName(), GWLogLevel.ALARM, "监控用户：" + userMonitorVO.getName() + "掉线");
                                    break;
                                case 2:
                                    log.warn(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "队列深度超出阀值");
                                    break;
                                case 4:
                                    log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "下线");
                                    break;
                            }
                            break;
                        case 4://灰
                            switch (thisTimeState) {
                                case 1:
                                    log.error(UserMonitorService.class, userMonitorVO.getName(), GWLogLevel.ALARM, "监控用户：" + userMonitorVO.getName() + "掉线");
                                    break;
                                case 2:
                                    log.warn(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "队列深度超出阀值");
                                    break;
                                case 3:
                                    log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "上线");
                                    break;
                            }
                            break;
                    }
                }

            } else {
                switch (thisTimeState) {
                    case 1:
                        log.error(UserMonitorService.class, userMonitorVO.getName(), GWLogLevel.ALARM, "监控用户：" + userMonitorVO.getName() + "掉线");
                        break;
                    case 2:
                        log.warn(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "队列深度超出阀值");
                        break;
                    case 3:
                        log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "上线");
                        break;
                    case 4:
                        log.info(UserMonitorService.class, userMonitorVO.getName(), "监控用户：" + userMonitorVO.getName() + "下线");
                        break;
                }
            }

        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "userLogRecord() error", e);
        }

    }

    /**
     * 获取CGW用户状态（从findAllUserMonitor（）中提取）
     * 2016-12-28 liuyi 创建
     *
     * @return
     */
    private Map<String, Object> getCGWUserStates(Map<String, LinkedHashMap<String, String>> map) {
        Map<String, Object> result = null;
        Map<String, UserMonitorVO> cgwUserSates = new HashMap<>();

        try {
            if (map != null) {
                result = new HashMap<>();
                LinkedHashMap<String, String> mapUserInfo = map.get("gw");
                //此处需要获取healthy，若为false，则用户监控不显示
                boolean healthy = Boolean.parseBoolean(new ObjectMapper().writeValueAsString(mapUserInfo.get("healthy")));
                result.put("healthy", healthy);
                Map<String, List<LinkedHashMap<String, Object>>> gwUserMap = new ObjectMapper().readValue(mapUserInfo.get("message"), Map.class);
                //模式
                String mode = new ObjectMapper().writeValueAsString(gwUserMap.get("mode")).replace("\"", "");
                result.put("mode", mode);
                List<LinkedHashMap<String, Object>> userListMap = gwUserMap.get("gwUser");//需判断普通模式还是应急模式
                for (LinkedHashMap<String, Object> map1 : userListMap) {
                    UserMonitorVO userMonitorVO = new UserMonitorVO();
                    //userid
                    userMonitorVO.setUserId(map1.get("id").toString());
                    //CgwState
                    userMonitorVO.setCgwState(map1.get("state").toString());
                    //name
                    userMonitorVO.setName(map1.get("name").toString());
                    //ip
                    userMonitorVO.setIp(map1.get("ip").toString());
                    //up
                    userMonitorVO.setUpMsgCount(Long.valueOf(map1.get("up").toString()));
                    //down
                    userMonitorVO.setDownMsgCount(Long.valueOf(map1.get("down").toString()));
                    //updateTime
                    userMonitorVO.setUpdateTime(map1.get("updateTime").toString());
                    cgwUserSates.put(userMonitorVO.getUserId(), userMonitorVO);
                }
                result.put("cgwUserSates", cgwUserSates);
            }
        } catch (IOException e) {
            log.error(UserMonitorServiceImpl.class, "getCGWUserStates() error", e);
        }
        return result;
    }

    /**
     * 获取告警标识（从findAllUserMonitor（）中提取）
     * 2016-12-28 liuyi 创建
     *
     * @param sendQueueName
     * @param recvQueueName
     * @return
     */
    public boolean checkQueueDepth(String sendQueueName, String recvQueueName) {
        // 发送队列深度
        long sendDepth = 0;
        // 接收队列深度
        long recDepth = 0;
        long MaxQueueDepth = 0;
        boolean flag = false;

        try {
            //最大队列深度
            MaxQueueDepth = Long.parseLong(sysConfigurationService.getValue(Constant.MQ_QUEUE_DEPTH));
            //MQ中队列深度
            Map<String, com.adcc.utility.mq.entity.Queue> map = getUserQueues(sendQueueName, recvQueueName);
            if (map != null) {
                sendDepth = map.get("sendQueue").getDepth();
                recDepth = map.get("recQueue").getDepth();

                //判断队列深度是否超阀值
                if (sendDepth > MaxQueueDepth || recDepth > MaxQueueDepth)
                    flag = true;
            }
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "checkQueueDepth() error", e);
        }
        return flag;
    }

    /**
     * 获取用户接收队列、发送队列
     * 2017-01-09 liuyi 创建
     *
     * @param sendQueueName
     * @param recvQueueName
     * @return
     */
    public Map<String, com.adcc.utility.mq.entity.Queue> getUserQueues(String sendQueueName, String recvQueueName) {
        Map<String, com.adcc.utility.mq.entity.Queue> map = null;
        try {
            map = new HashMap<>();
            //MQserver中的队列深度
            MQManager mqManagerGW1 = mqFactory.getSourceMQM();
            List<com.adcc.utility.mq.entity.Queue> sendQueues = mqManagerGW1.findQueue(sendQueueName);
            List<com.adcc.utility.mq.entity.Queue> recQueues = mqManagerGW1.findQueue(recvQueueName);
            for (com.adcc.utility.mq.entity.Queue queue : sendQueues) {
                if (queue.getName().equals(sendQueueName)) {
                    map.put("sendQueue", queue);
                }
            }
            for (com.adcc.utility.mq.entity.Queue queue : recQueues) {
                if (queue.getName().equals(recvQueueName)) {
                    map.put("recQueue", queue);
                }
            }
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "getUserQueues() error", e);
        }
        return map;
    }

    /**
     * 普通模式用户处理
     *
     * @param gwUser
     * @param CGWUserMap
     * @return
     */
    public UserMonitorVO normalMode(GWUser gwUser, Map<String, UserMonitorVO> CGWUserMap) {
        UserMonitorVO userMonitorVO = new UserMonitorVO();
        try {
            int effect = gwUser.getStatus();
            //本地上线
            if (effect == 1) {
                UserMonitorVO CGWUser = null;
                //匹配是否对应
                if (CGWUserMap.get(gwUser.getUserId()) != null) {//正常
                    CGWUser = CGWUserMap.get(gwUser.getUserId());
                    if ("ONLINE".equals(CGWUser.getCgwState())) {
                        //判断队列深度是否超阀值
                        if (checkQueueDepth(gwUser.getSendQueueName(), gwUser.getRecvQueueName())) {
                            userMonitorVO.setState(2);//黄色
                            userMonitorVO.setMessage("告警,用户队列深度超阀值");
                        } else {
                            userMonitorVO.setState(3);//绿色
                            userMonitorVO.setMessage("在线");
                        }
                        userMonitorVO.setIp(CGWUser.getIp());
                    } else if ("OFFLINE".equals(CGWUser.getCgwState())) {
                        userMonitorVO.setState(1);//红色
                        userMonitorVO.setMessage("掉线");
                        userMonitorVO.setIp(gwUser.getUserIP());
                    }
                    userMonitorVO.setName(CGWUser.getName());
                    userMonitorVO.setUpdateTime(CGWUser.getUpdateTime());
                    userMonitorVO.setUpMsgCount(CGWUser.getUpMsgCount());
                    userMonitorVO.setDownMsgCount(CGWUser.getDownMsgCount());
                } else {//异常
                    userMonitorVO.setState(1);
                    userMonitorVO.setMessage("掉线");
                    userMonitorVO.setIp(gwUser.getUserIP());
                    userMonitorVO.setName(gwUser.getUserName());
                }

            } else if (effect == 0) {//本地下线
                userMonitorVO.setState(4);
                userMonitorVO.setMessage("本地已下线");
                userMonitorVO.setName(gwUser.getUserName());
                userMonitorVO.setIp(gwUser.getUserIP());
            }
            //获取用户发送队列和接收队列具体信息
            Map<String, com.adcc.utility.mq.entity.Queue> userQueues = getUserQueues(gwUser.getSendQueueName(), gwUser.getRecvQueueName());
            if (userQueues != null && userQueues.size() > 0) {
                com.adcc.utility.mq.entity.Queue sendQueue = userQueues.get("sendQueue");
                com.adcc.utility.mq.entity.Queue recQueue = userQueues.get("recQueue");
                userMonitorVO.setSendQueueName(sendQueue.getName());
                userMonitorVO.setSendQueueDepth(sendQueue.getDepth());
                userMonitorVO.setRecQueueName(recQueue.getName());
                userMonitorVO.setRecQueueDepth(recQueue.getDepth());
            }
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "normalMode() error", e);
        }
        return userMonitorVO;
    }

    /**
     * 应急模式、CGW异常处理
     *
     * @param CGWUser
     * @param gwUser
     * @return
     */
    public UserMonitorVO emergencyMode(UserMonitorVO CGWUser, GWUser gwUser) {
        UserMonitorVO userMonitorVO = new UserMonitorVO();
        try {
            Map<String, com.adcc.utility.mq.entity.Queue> userQueues = getUserQueues(gwUser.getSendQueueName(), gwUser.getRecvQueueName());
            com.adcc.utility.mq.entity.Queue sendQueue = null;
            com.adcc.utility.mq.entity.Queue recQueue = null;
            if (CGWUser != null) {
                if ("ONLINE".equals(CGWUser.getCgwState())) {
                    //判断队列深度是否超阀值
                    if (checkQueueDepth(gwUser.getSendQueueName(), gwUser.getRecvQueueName())) {
                        userMonitorVO.setState(2);//黄色
                        userMonitorVO.setMessage("应急告警,用户队列深度超阀值");
                    } else {
                        userMonitorVO.setState(3);//绿色
                        userMonitorVO.setMessage("应急在线");
                    }
                    userMonitorVO.setIp(CGWUser.getIp());
                } else if ("OFFLINE".equals(CGWUser.getCgwState())) {
                    userMonitorVO.setState(1);
                    userMonitorVO.setMessage("应急掉线");
                    userMonitorVO.setIp(gwUser.getUserIP());
                }
                userMonitorVO.setName(CGWUser.getName());
                userMonitorVO.setUpdateTime(CGWUser.getUpdateTime());
                userMonitorVO.setUpMsgCount(CGWUser.getUpMsgCount());
                userMonitorVO.setDownMsgCount(CGWUser.getDownMsgCount());
                //获取用户发送队列和接收队列具体信息
                if (userQueues != null && userQueues.size() > 0) {
                    sendQueue = userQueues.get("sendQueue");
                    recQueue = userQueues.get("recQueue");
                    userMonitorVO.setSendQueueName(sendQueue.getName());
                    userMonitorVO.setSendQueueDepth(sendQueue.getDepth());
                    userMonitorVO.setRecQueueName(recQueue.getName());
                    userMonitorVO.setRecQueueDepth(recQueue.getDepth());
                }
            } else if (CGWUser == null && gwUser != null) {
                userMonitorVO = excepMode(null, gwUser);
            }
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "emergencyMode() error", e);
        }
        return userMonitorVO;
    }

    /**
     * 异常处理
     *
     * @param CGWUser
     * @param gwUser
     * @return
     */
    public UserMonitorVO excepMode(UserMonitorVO CGWUser, GWUser gwUser) {
        UserMonitorVO userMonitorVO = null;
        try {
            if (CGWUser != null && gwUser == null) {
                if ("ONLINE".equals(CGWUser.getCgwState())) {
                    CGWUser.setState(3);
                    CGWUser.setMessage("应急在线");
                } else if ("OFFLINE".equals(CGWUser.getCgwState())) {
                    CGWUser.setState(1);
                    CGWUser.setMessage("应急掉线");
                }
                userMonitorVO = CGWUser;
            } else if (CGWUser == null && gwUser != null) {
                userMonitorVO = new UserMonitorVO();
                if (gwUser.getStatus() == 1) {
                    userMonitorVO.setState(1);
                    userMonitorVO.setMessage("掉线");
                } else if (gwUser.getStatus() == 0) {
                    userMonitorVO.setState(4);
                    userMonitorVO.setMessage("本地已下线");
                }
                userMonitorVO.setIp(gwUser.getUserIP());
                userMonitorVO.setName(gwUser.getUserName());

                Map<String, com.adcc.utility.mq.entity.Queue> userQueues = getUserQueues(gwUser.getSendQueueName(), gwUser.getRecvQueueName());
                //获取用户发送队列和接收队列具体信息
                if (userQueues != null && userQueues.size() > 0) {
                    com.adcc.utility.mq.entity.Queue sendQueue = userQueues.get("sendQueue");
                    com.adcc.utility.mq.entity.Queue recQueue = userQueues.get("recQueue");
                    userMonitorVO.setSendQueueName(sendQueue.getName());
                    userMonitorVO.setSendQueueDepth(sendQueue.getDepth());
                    userMonitorVO.setRecQueueName(recQueue.getName());
                    userMonitorVO.setRecQueueDepth(recQueue.getDepth());
                }
            }
        } catch (Exception e) {
            log.error(UserMonitorServiceImpl.class, "excepMode() error", e);
        }
        return userMonitorVO;
    }

    /**
     * 取得rest接口服务状态
     *
     * @param url
     * @return
     */
    public Map<String, LinkedHashMap<String, String>> getRestService(String url) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpGet.setConfig(requestConfig);
            client = HttpClients.createDefault();
            response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 500) {
                InputStream is = response.getEntity().getContent();
                Map<String, LinkedHashMap<String, String>> map = new ObjectMapper().readValue(CommonUtil.getString(is), Map.class);
                return map;
            } else {
                return null;
            }
        } catch (Exception ex) {
            log.error(UserMonitorServiceImpl.class, "getRestService() error", ex);
            return null;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }

            } catch (Exception e) {
                log.error(UserMonitorServiceImpl.class, "close io error", e);
            }
        }
    }

    @Override
    public Optional<String> checkNet(String cmd, String ip, String pingNum) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String resultString = null;
        //硬件监控地址
        String url = sysConfigurationService.getValue(Constant.GW_NETWORK_MONITOR_URL) + cmd;
        try {
            HttpPost httpPost = new HttpPost(url);

            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(25000)
                    .setConnectTimeout(25000)
                    .build();
            httpPost.setConfig(requestConfig);
            client = HttpClients.createDefault();
            //参数（CMD命令）
            List<BasicNameValuePair> list = Lists.newArrayListWithExpectedSize(2);
            list.add(new BasicNameValuePair("ip", ip));
            //linux ping操作 需要加次数 -c pingNum
            if (url.contains("ping")) {
                list.add(new BasicNameValuePair("count", pingNum));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            client.execute(httpPost);
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity());
            }
            return Optional.of(resultString);
        } catch (Exception ex) {
            log.error(UserMonitorService.class, "checkNet() error", ex);
            return Optional.absent();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    log.error(UserMonitorService.class, "close responseIO error", ex);
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException ex) {
                    log.error(UserMonitorService.class, "close clientIO error", ex);
                }
            }
        }
    }
}



